/**
 * Description:
 * Class Name:TransactionTest
 * Date:2022/4/10 18:06
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_7_事务处理._13_7_2_JDBC的事务支持;

import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

public class TransactionTest {
    private String driver;
    private String url;
    private String user;
    private String pwd;

    public void initParam(String paramFilePath) throws Exception{
        Properties props = new Properties();
        props.load(new FileReader(paramFilePath));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }

    public void insertInTransaction(String[] sqls) throws Exception{
        try (
                Connection connection = DriverManager.getConnection(url, user, pwd)
                ){
            // 先获取connection的autoCommit状态是什么
            System.out.println("connection的autoCommit状态是：" + connection.getAutoCommit());
            // 关闭自动提交，也就是开启事务
            connection.setAutoCommit(false);
            System.out.println("关闭自动提交后connection的autoCommit状态是：" + connection.getAutoCommit());
            try (
                    Statement statement = connection.createStatement()
                    ){
                // 循环多次执行SQL语句
                for (var sql :
                        sqls) {
                    statement.executeUpdate(sql);
                }
            }
            // 提交事务
            connection.commit();
        }
    }

    public static void main(String[] args) throws Exception{
        var tt = new TransactionTest();
        tt.initParam("Chapter_13_mysql.ini");
        Class.forName(tt.driver);

        String[] sqls = new String[]{
          "insert into student_table values (null, 'aaa', 1)",
          "insert into student_table values (null, 'bbb', 1)",
          "insert into student_table values (null, 'ccc', 1)",
          // 下面这条SQL语句将会违反外键约束，因为teacher_table中没有id为5的老师
          "insert into student_table values (null, 'ddd', 5)",
        };

        tt.insertInTransaction(sqls);
    }
}
